package com.example.video.view

import android.content.Context
import android.graphics.Point
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.Surface
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.SeekBar
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.danikula.videocache.Cache
import com.example.video.R
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.utils.NetInfoModule
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer


/**
 * 自定义GSY视频播放器
 * */
class CoverVideoPlayerView constructor(private val context : Context,private val attrs :AttributeSet): StandardGSYVideoPlayer(context,attrs) {


    private lateinit var mCoverImageView : ImageView
     lateinit var rvContent :RelativeLayout
    private var byStartedClick = false
    private var mCoverOriginUrl =""
    private var mDefaultRes = 0



    //返回布局
    override fun getLayoutId(): Int = R.layout.video_view_layout

    /**
     * 设置视频链接地址
     * */
    fun setVideoUrl(videoUrl :String){
        mUrl=videoUrl
        mOriginUrl=videoUrl
    }
    /**
     * 设置缓存
     * */
    fun setVideoCache(cache: Boolean){
        mCache=cache
    }
    /**
     * 设置标题
     * */
    fun setVideoTitle(title : String){
        mTitle=title
    }

    /**
     * 设置封面图
     * */
    fun setCoverImage(url :String,resId :Int){
        mCoverOriginUrl=url
        mDefaultRes=resId
        //加载图片
        Glide.with(context.applicationContext).load(url).apply(RequestOptions.bitmapTransform(
            RoundedCorners(10)
        )).into(mCoverImageView)
    }

    /**
     * 保持播放器状态
     * */
    fun saveState() : CoverVideoPlayerView{
        var coverVideo = CoverVideoPlayerView(context,attrs)
        cloneParams(this,coverVideo)
        return coverVideo
    }

    /**
     * 克隆播放器
     * */

    fun cloneState(coverVideo : CoverVideoPlayerView){
        cloneParams(coverVideo,this)
    }




    /**
     * c初始化
     * */
    override fun init(context: Context?) {
        super.init(context)
        mCoverImageView=findViewById(R.id.thumbImage)
        rvContent=findViewById(R.id.surface_container)
        //控制封面图片的布局
        if (mThumbImageViewLayout!=null &&(mCurrentState==-1 || mCurrentState== CURRENT_STATE_NORMAL || mCurrentState== CURRENT_STATE_ERROR)){
            mThumbImageViewLayout?.visibility=View.VISIBLE
        }
    }


    /**
     * 全屏播放
     * */
    override fun startWindowFullscreen(
        context: Context?,
        actionBar: Boolean,
        statusBar: Boolean
    ): GSYBaseVideoPlayer {
        return super.startWindowFullscreen(context, actionBar, statusBar)
    }


    /**
     * 小窗播放
     * */
    override fun showSmallVideo(
        size: Point?,
        actionBar: Boolean,
        statusBar: Boolean
    ): GSYBaseVideoPlayer {
       var smallCoverVideoView= super.showSmallVideo(size, actionBar, statusBar) as CoverVideoPlayerView
        smallCoverVideoView.mStartButton.visibility=View.GONE
        smallCoverVideoView.mStartButton=null
        return smallCoverVideoView

    }
    /**
     * 克隆参数
     * */
    override fun cloneParams(from: GSYBaseVideoPlayer?, to: GSYBaseVideoPlayer?) {
        super.cloneParams(from, to)
        //show全屏的动画
        var fromVideoView = from as CoverVideoPlayerView
        var toVideoView = to as CoverVideoPlayerView
        toVideoView.mShowFullAnimation = fromVideoView.mShowFullAnimation
    }
    /**
     * 清楚全屏播放布局
     * */
    override fun clearFullscreenLayout() {
       if (!mFullAnimEnd){
           return
       }
        mIfCurrentIsFullscreen =false
        var delay =0
        if (mOrientationUtils!=null){
            delay=mOrientationUtils.backToProtVideo()
            mOrientationUtils.isEnable=false
            if (mOrientationUtils!=null){
                mOrientationUtils.releaseListener()
                mOrientationUtils=null
            }
        }

        if (!mShowFullAnimation){
            delay = 0
        }
        val vp =viewGroup
        val oldF = vp.findViewById<View>(fullId)
        if (oldF!= null){
            //退出全屏的时候 虚拟按键问题
            val gsyVideoPlayer = oldF as CoverVideoPlayerView
            gsyVideoPlayer.mIfCurrentIsFullscreen =false
        }
        mInnerHandler.postDelayed({backToNormal()},delay.toLong())
    }
    /**
     * 窗口更新
     * */
    override fun onSurfaceUpdated(surface: Surface?) {
        super.onSurfaceUpdated(surface)
        //设置封面图片布局显示
        if(mThumbImageViewLayout!= null && mThumbImageViewLayout.visibility==View.VISIBLE){
            mThumbImageViewLayout?.visibility==View.INVISIBLE
        }
    }
    /**
     * 设置组件显示状态
     * */
    override fun setViewShowState(view: View?, visibility: Int) {
        if (view== mThumbImageViewLayout && visibility!=View.VISIBLE) return
        super.setViewShowState(view, visibility)
    }
    /**
     * 窗口可用
     * */
    override fun onSurfaceAvailable(surface: Surface?) {
        super.onSurfaceAvailable(surface)
        if (GSYVideoType.getRenderType() != GSYVideoType.TEXTURE){
            if (mThumbImageViewLayout!=null && mThumbImageViewLayout.visibility==View.VISIBLE){
                mThumbImageViewLayout.visibility==View.INVISIBLE
            }
        }
    }

    /**
     * 点击UI开关
     * */
    override fun onClickUiToggle(e: MotionEvent?) {
        if (mIfCurrentIsFullscreen && mLockCurScreen && mNeedLockFull) {
            setViewShowState(mLockScreen, VISIBLE)
            return
        }
        byStartedClick = true
        super.onClickUiToggle(e)
    }

    /**
     * UI切换到普通模式
     * */

    override fun changeUiToNormal() {
        super.changeUiToNormal()
        byStartedClick =false
    }
    /**
     * UI准备显示回调
     * */
    override fun changeUiToPreparingShow() {
        super.changeUiToPreparingShow()
        setViewShowState(mBottomContainer, INVISIBLE)
        setViewShowState(mStartButton, INVISIBLE)
    }
    /**
     *UI缓冲时回调
     * */
    override fun changeUiToPlayingBufferingShow() {
        super.changeUiToPlayingBufferingShow()
        if (!byStartedClick){
            setViewShowState(mBottomContainer, INVISIBLE)
            setViewShowState(mStartButton, INVISIBLE)
        }
    }
    /**
     *UI正在播放
     * */
    override fun changeUiToPlayingShow() {
        super.changeUiToPlayingShow()
        if (!byStartedClick) {
            setViewShowState(mBottomContainer, INVISIBLE)
            setViewShowState(mStartButton, INVISIBLE)
        }
    }
    /**
     *准备完成之后播放
     * */
    override fun startAfterPrepared() {
        super.startAfterPrepared()
        setViewShowState(mBottomContainer, INVISIBLE)
        setViewShowState(mStartButton, INVISIBLE)
        setViewShowState(mBottomProgressBar, VISIBLE)
    }
    /**
     *开始拖拽事件回调
     * */
    override fun onStartTrackingTouch(seekBar: SeekBar?) {
        byStartedClick=true
        super.onStartTrackingTouch(seekBar)
    }


    /**
     * 取消播放
     * 利用反射解决GSY库中网络监听事件导致的内存泄漏问题
     */
    fun cancel(){
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener)

        try {
            if (mNetInfoModule != null){
                //拿到NetInfoModule对象中的字段 mConnectivityBroadcastReceiver字段
                val mConnectivityBroadcastReceiver =NetInfoModule::class.java.getDeclaredField("mConnectivityBroadcastReceiver")
                //由于是私有字段 所以调用setAccessible方法
                mConnectivityBroadcastReceiver.isAccessible=true
                // 根据当前mNetInfoModule对象的 mConnectivityBroadcastReceiver字段值为null
                mConnectivityBroadcastReceiver[mNetInfoModule]=null

                //把网络状态监听器设置为null
                val mNetChangeListener = NetInfoModule::class.java.getDeclaredField("mNetChangeListener")
                mNetChangeListener.isAccessible =true
                mNetChangeListener[mNetInfoModule] = null
             }

        }catch (e: NoSuchFieldException){
            e.printStackTrace()
        }catch (e: IllegalAccessException){
            e.printStackTrace()
        }
    }


}